package com.aube.base.util;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;

import com.huyn.baseframework.utils.Utils;

import java.lang.ref.WeakReference;

/**
 * Created by hill on 16/12/14.
 */

public class CustomImageSpan extends ImageSpan {
    public static final int ALIGN_TOP = 2;

    public CustomImageSpan(final Drawable drawable, final int verticalAlignment) {
        super(drawable, verticalAlignment);
    }

    @Override
    public void draw(Canvas canvas, CharSequence text,
                     int start, int end, float x,
                     int top, int y, int bottom, Paint paint) {
        Drawable b = getCachedDrawable();
        canvas.save();

        int transY = bottom - b.getBounds().bottom;
        if (mVerticalAlignment == ALIGN_BASELINE) {
            transY -= paint.getFontMetricsInt().descent;
        } else if (mVerticalAlignment == ALIGN_TOP) {
            transY += paint.getFontMetricsInt().ascent;
        }

        transY = ((bottom - top) - b.getBounds().bottom) / 2 + top;
        //Utils.Log("VSViewEx", "draw: transY = " + transY + ", bottom = " + bottom + ", top = " + top + ", b.getBounds().bottom = " + b.getBounds().bottom);

        canvas.translate(x, transY);
        b.draw(canvas);
        canvas.restore();
    }
    private Drawable getCachedDrawable() {
        WeakReference<Drawable> wr = mDrawableRef;
        Drawable d = null;

        if (wr != null)
            d = wr.get();

        if (d == null) {
            d = getDrawable();
            mDrawableRef = new WeakReference<Drawable>(d);
        }

        return d;
    }

    private WeakReference<Drawable> mDrawableRef;
}